from django.shortcuts import render
from django.views import View
from goods.models import GoodsChannelGroup,GoodsChannel,GoodsCategory
from collections import OrderedDict # 导入有序字典
from contents.models import ContentCategory,Content # 导入广告类别和广告内容
from contents.utils import get_categories

# Create your views here.
class IndexView(View):
    def get(self,request):
        """提供首页广告页面"""
        # 查询并展示商品分类
        categories=get_categories()
        # 查询首页广告数据
        # 查询所有的广告类别
        contents = OrderedDict()
        content_categories=ContentCategory.objects.all()
        for content_category in content_categories:
            # status=True：表示广告未下架
            # 查询出所有未下架的广告
            contents[content_category.key]=content_category.content_set.filter(status=True).order_by("sequence")

        # 使用广告类别查询出该类别对应的所有广告内容
        # 构造上下文
        context={
            "categories":categories,
            "contents":contents
        }

        from django.middleware.csrf import rotate_token, get_token
        rotate_token(request)  # 生成csrftoken随机字符串
        csrftoken = get_token(request)  # 取出csrftoken随机字符串
        response =render(request,"index.html",context=context)
        response.set_cookie("csrftoken", csrftoken, max_age=15 * 24 * 3600)

        return response
